package com.reading.core.manager.impl;

import com.reading.common.cache.service.CacheService;
import com.reading.common.config.SequenceConfig;
import com.reading.common.entity.view.User;
import com.reading.common.entity.view.UserPassword;
import com.reading.common.persistence.view.UserMapper;
import com.reading.common.persistence.view.UserPasswordMapper;
import com.reading.common.utils.StringUtil;
import com.reading.core.exception.AloneException;
import com.reading.core.exception.user.LoginAccountPasswordFailException;
import com.reading.core.exception.user.LoginAccountNotExistsException;
import com.reading.core.exception.user.RegisterAccountAlreadyExistsException;
import com.reading.core.exception.user.RegisterException;
import com.reading.core.manager.IUserManager;
import com.reading.core.utils.CheckUtil;
import com.reading.core.utils.GlobalConstant;
import com.reading.core.utils.PasswordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author guwenqi_1995@163.com
 * @date 2019/7/8 1:37 PM
 **/
@Slf4j
@Service
public class UserManagerImpl implements IUserManager {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserPasswordMapper userPasswordMapper;

    @Resource
    private CacheService cacheService;

    @Resource
    private SequenceConfig sequenceConfig;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean register(User user, String validatorCode) throws AloneException {
        CheckUtil.valid(user);
        CheckUtil.isNull(validatorCode);

        //关闭邮箱验证
//        boolean isTrue = cacheService.checkEmailCode(user.getUserEmail(), validatorCode);
//        if (!isTrue) {
//            log.error("");
//            throw new AloneException(ExceptionCode.CHECK_EMAILCODE_ERROR);
//        }

        if (StringUtil.isNotNull(userMapper.selectByEmail(user.getUserEmail()))) {
            log.error("注册失败，账号已存在。");
            throw new RegisterAccountAlreadyExistsException();
        }

        //保存用户信息
        int userId = sequenceConfig.getUserId();
        user.setUserId(userId);
        user.setNickName(GlobalConstant.getRandomNickName() + userId);
        user.setUserGender(GlobalConstant.USER_INIT_GENDER);
        user.setHeadImg(GlobalConstant.USER_INIT_HEAD_IMG);
        user.setUserStatus(GlobalConstant.USER_INIT_STATUS);
        user.setUserDescr(GlobalConstant.USER_INIT_DESCR);
        if (userMapper.insert(user) <= 0) {
            log.error("注册失败。{}", user.toString());
            throw new RegisterException();
        }

        //保存用户密码信息
        String salt = PasswordUtil.randomSalt();
        String password = PasswordUtil.encryptPassword(user.getUserEmail(),user.getPassword(), salt);
        UserPassword userPassword = new UserPassword(userId, password, salt);
        if (userPasswordMapper.insert(userPassword) <= 0) {
            log.error("注册失败。{}，{}", password, salt);
            throw new RegisterException();
        }
        return true;
    }

    @Override
    public User login(String email, String password) throws AloneException {
        if (!CheckUtil.validateEmail(email) || !CheckUtil.validatePass(password)) {
            log.error("登入失败，用户名或密码错误。{}, {}", email, password);
            throw new LoginAccountPasswordFailException();
        }

        User user = userMapper.selectByEmail(email);
        if (StringUtil.isNull(user)) {
            log.error("登入失败，账号不存在。{}", email);
            throw new LoginAccountNotExistsException();
        }

        UserPassword passInfo = userPasswordMapper.selectByPrimaryKey(user.getUserId());
        Boolean isTrue = PasswordUtil.matches(email, password, passInfo.getSalt(), passInfo.getPassword());
        if (!isTrue) {
            log.error("登入失败，用户名或密码错误。{}, {}", email, password);
            throw new LoginAccountPasswordFailException();
        }
        return user;
    }

    @Override
    public Boolean saveUser(User user) throws AloneException {
        log.error("暂不支持该方法。");
        return false;
    }

    @Override
    public Boolean modifyUserInfo(User user) throws AloneException {
        log.error("暂不支持该方法。");
        return null;
    }
}
